package priv.wangy.micro.common.config.feign.decoder;

import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.NamedThreadLocal;
import priv.wangy.micro.common.utils.JsonUtil;

import java.lang.reflect.Type;
import java.util.Objects;

/**
 * @author zhangjq
 * @since 2023-10-31
 */
@Slf4j
public class FullHttpRspnDecoder implements Decoder {

    private static final NamedThreadLocal<Class<?>> FEIGN_RSPN_TYPE_THREAD_LOCAL = new NamedThreadLocal<>("feignRspnTypeThreadLocal");

    public static void setRspnType(Class<?> rspnType) {
        FEIGN_RSPN_TYPE_THREAD_LOCAL.set(rspnType);
    }

    @Override
    public Object decode(Response response, Type type) throws FeignException {
        try {
            if (response.body() == null) {
                throw new DecodeException(response.status(), "invalid response data", response.request());
            }
            String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
            if (Objects.nonNull(FEIGN_RSPN_TYPE_THREAD_LOCAL.get())) {
                return JsonUtil.readComplexJson(bodyStr, type, FEIGN_RSPN_TYPE_THREAD_LOCAL.get());
            }
            return JsonUtil.readJson(bodyStr, type);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            FEIGN_RSPN_TYPE_THREAD_LOCAL.remove();
        }
        return null;
    }
}
